<template>
  <div class="app-main-container">
    <div class="df" style="height: 100%;">
      <div class="w400 sell_left">
        <el-input
          v-model="mealName"
          :placeholder="$t('message.qsr') + $t('message.tcname')"
          class="input-with-select bottom-speace-style"
          @keyup.enter.native="searchMeals"
        >
          <el-button slot="append" icon="el-icon-search" @click="searchMeals" />
        </el-input>
        <div class="sell_wrap">
          <div class="mt10">
            <div
              v-for="(item, index) in saleTickets"
              :key="index"
              class="card-style"
              :class="item.isSelect?'select-style':'normal-style'"
              @click="selectTick(index)"
            >
              <div class="img-div">
                <img v-if="item.imgurl" :src="item.imgurl" alt="">
                <img v-else src="@/assets/images/default_meal_img.jpg" alt="">
              </div>
              <div class="combo_card_right">
                <div class="card-name">{{ item.name }}</div>
                <div v-if="item.mealsType === '0'" class="card_type">{{ $t('message.tclx') }}：{{ $t('message.mpcsk') }}</div>
                <div v-if="item.mealsType === '1'" class="card_type">{{ $t('message.tclx') }}：{{ $t('message.mpqxk') }}</div>
                <div v-if="item.mealsType === '2'" class="card_type">{{ $t('message.tclx') }}：{{ $t('message.ydck') }}</div>
                <div v-if="item.mealsType === '3'" class="card_type">{{ $t('message.tclx') }}：{{ $t('message.kcyyck') }}</div>
                <div v-if="item.mealsType === '4'" class="card_type">{{ $t('message.tclx') }}：{{ $t('message.ykyyqxk') }}</div>
                <div v-if="item.validityType == '2'" class="time-style">{{ $t('message.yxq') }}：{{ item.assignValidTime }}{{ $t('message.kssx') }}，{{ $t('message.yxq') }}{{ item.indate }}{{ $t('message.tian') }}</div>
                <div v-if="item.validityType == '1'" class="time-style">{{ $t('message.yxq') }}：{{ $t('message.zgmzrq') }}{{ item.indate }}{{ $t('message.tyx') }}</div>
                <div v-if="item.validityType == '0'" class="time-style">{{ $t('message.yxq') }}：{{ item.validityStartTime + " - " + item.validityEndTime }}</div>
                <div class="specific">
                  <div class="card-first-price secondColor">{{ $t('message.rmbfh') }}{{ item.price }}</div>
                  <div class="num-module-style">
                    <div class="sale-style">
                      <span class="num-title-style">{{ $t('message.yishou') }}：</span>
                      <span>{{ item.circulationDay - item.surplusDay }}</span>
                    </div>
                    <span class="ml10 mr10 placeholder6"> | </span>
                    <div class="surplus-style">
                      <span class="num-title-style">{{ $t('message.sy') }}：</span>
                      <span>{{ item.surplusDay }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div>
          <Pagination
            :integrated="false"
            :page="salePagination.page"
            :total="saleTotal"
            :page-size="salePagination.rows"
            @current-change="salePageChange"
          />
        </div>
      </div>
      <div class="separator" />
      <div class="flex1">
        <div class="member_wrap">
          <div class="df">
            <MemberSearch ref="MemberSearchRef" class="flex1" @clear="memberClear" @select="memberSelect" />
            <el-button
              v-if="memberInfo.nickName"
              class="ml10"
              type="primary"
              @click="showAddBtn"
            >{{ $t('message.xzxy') }}</el-button>
            <!-- <el-button class="ml10" type="primary" @click="memberClear">{{ $t('message.sk') }}</el-button> -->
          </div>
          <div class="df mt20 mb20">
            <span class="flex1">{{ $t('message.name') }}：{{ memberInfo.nickName || '-' }}</span>
            <span class="flex1">{{ $t('message.sjh') }}：{{ memberInfo.phone || '-' }}</span>
            <span class="flex1">{{ $t('message.hydj') }}：{{ memberInfo.cardName || '-' }}</span>
            <span class="flex1">{{ $t('message.czje') }}：{{ memberInfo.rechargeMoney || '0.00' }}</span>
            <span class="flex1">{{ $t('message.zsye') }}：{{ memberInfo.giveMoney || '0.00' }}</span>
          </div>
        </div>
        <div class="tables">
          <el-table
            :data="selectedMessage"
            border
            fit
            :header-row-class-name="'table-header'"
            class="doumee-element-table"
          >
            <el-table-column align="center" :label="$t('message.tc')" prop="name" min-width="100" show-overflow-tooltip />
            <el-table-column align="center" :label="$t('message.cs')" prop="nums" min-width="60" show-overflow-tooltip />
            <el-table-column align="center" :label="$t('message.zscs')" width="120">
              <template slot-scope="scope">
                <el-input-number v-if="scope.row.mealsType !== '1'" v-model="scope.row.giveNums" :disabled="!zsnum" size="small" :step="1" step-strictly :min="0" :max="9999" :label="$t('message.zscs')" style="width: 100%" />
              </template>
            </el-table-column>
            <el-table-column align="center" :label="$t('message.dprice')" prop="price" min-width="50" show-overflow-tooltip />
            <el-table-column align="center" :label="$t('message.num')" width="120">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.num" size="small" step-strictly :max="scope.row.surplusDay" :step="1" :min="1" :label="$t('message.num')" style="width: 100%" />
              </template>
            </el-table-column>
            <el-table-column align="center" :label="$t('message.xueyuan')" width="160">
              <template v-if="scope.row.mealsType === '3' || scope.row.mealsType === '4'" slot-scope="scope">
                <el-select
                  v-model="scope.row.student"
                  multiple
                  size="small"
                  collapse-tags
                  clearable
                  filterable
                  :placeholder="$t('message.qxz') + $t('message.xueyuan')"
                >
                  <el-option
                    v-for="item in studentList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column align="center" :label="$t('message.jiaolian')" width="140">
              <template v-if="scope.row.mealsType === '3' || scope.row.mealsType === '4'" slot-scope="scope">
                <el-select
                  v-model="scope.row.teacherId"
                  size="small"
                  clearable
                  :placeholder="$t('message.qxz') + $t('message.jiaolian')"
                >
                  <el-option
                    v-for="item in scope.row.teachList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column align="center" :label="$t('message.xiaoji')" prop="price" min-width="50" show-overflow-tooltip />
            <el-table-column align="center" :label="$t('message.caozuo')" min-width="50" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-button v-preventReClick type="text" class="secondColor" @click="toDelete(scope.$index)">{{ $t('message.del') }}</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-if="selectedMessage.length" class="final_wrap">
          <div class="price_wrap">
            <div class="sum-style">
              <span class="sum-title">{{ $t('message.heji') }} ：</span>
              <span class="sum-value secondColor">{{ totalMoney }}</span>
            </div>
          </div>
          <div class="sub_order">
            <el-input v-model="remark" :placeholder="$t('message.qsr') + $t('message.ddbz')" />
            <el-button v-preventReClick :loading="subLoading" class="ml20" type="primary" @click="createOrder">{{ $t('message.ddjs') }} </el-button>
            <el-button @click="clearOrder">{{ $t('message.clear') }}</el-button>
          </div>
        </div>
      </div>
    </div>
    <orderDialog ref="child" @orderSuccess="orderSuccess" />
    <comboConfirm ref="comboConfirm" @openSuccess="subLoading = false" @confirm="createOrder" />
    <el-dialog
      :title="$t('message.xzxy')"
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
      :visible.sync="showStudent"
    >
      <el-form
        ref="formStudent"
        :model="formStudent"
        label-width="auto"
        :rules="ruleb"
        label-suffix="："
      >
        <el-form-item prop="name" :label="$t('message.xyxm')">
          <el-input
            v-model="formStudent.name"
            maxlength="50"
            :placeholder="$t('message.qsr') + $t('message.xyxm')"
            clearable
          />
        </el-form-item>
        <el-form-item prop="sex" :label="$t('message.xyxb')">
          <el-select
            v-model="formStudent.sex"
            style="width: 100%"
            :placeholder="$t('message.qxz') + $t('message.sex')"
          >
            <el-option value="1" :label="$t('message.nan')" />
            <el-option value="2" :label="$t('message.nv')" />
            <el-option value="0" :label="$t('message.bm')" />
          </el-select>
        </el-form-item>
        <el-form-item prop="birthday" :label="$t('message.csrq')">
          <el-date-picker
            v-model="formStudent.birthday"
            type="date"
            value-format="yyyy-MM-dd"
            :placeholder="$t('message.qxz') + $t('message.csrq')"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item prop="idCard" :label="$t('message.sfzh')">
          <el-input
            v-model="formStudent.idCard2"
            maxlength="18"
            :placeholder="$t('message.qsr') + $t('message.xysfzh')"
            clearable
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showStudent = false">{{ $t('message.qx') }}</el-button>
        <el-button :loading="subStuLoading" type="primary" @click="onSubmitb">{{ $t('message.baocun') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mealList, configList, studentAdd, studentListByMember, tcTeacherList } from '@/api'
import { parseTime } from '@/utils'
import orderDialog from '@/components/order'
import comboConfirm from '@/components/ComboConfirm'
import Pagination from '@/components/paginations'
import MemberSearch from '@/components/MemberSearch'
import store from '@/store'
export default {
  name: 'ComboSell',
  components: {
    orderDialog,
    comboConfirm,
    Pagination,
    MemberSearch
  },
  data() {
    return {
      modalDialog: store.getters.dialog,
      subLoading: false,
      mealName: '',
      ruleb: {
        name: [{ required: true, message: this.$t('message.qsr') + this.$t('message.xyxm'), trigger: 'blur' }]
      },
      subStuLoading: false,
      cardNum: '',
      dialogMessageTableVisible: false,
      dialogTableVisible: false,
      showMessage: false,
      cardMessage: {},
      date: null,
      zsnum: false,
      saleTickets: [],
      salePagination: {
        page: 1,
        rows: 20
      },
      saleTotal: 0,
      salePage: 1,
      selectedMessage: [],
      project: {
        projectList: []
      },
      param: {
        date: parseTime(new Date())
      },
      showStudent: false,
      studentList: [],
      formStudent: {},
      remark: '',
      memberInfo: {}
    }
  },
  computed: {
    // swiper() {
    //   return this.$refs.mySwiper.$swiper
    // },
    totalMoney() {
      let money = 0.0
      this.selectedMessage.forEach(item => {
        money += item.price * item.num
      })
      return parseFloat(money).toFixed(2)
    }
  },
  created() {
    this.getMeals()
    this.getDefalutConfig()
  },
  methods: {
    orderSuccess() {
      setTimeout(() => {
        this.memberClear()
        this.clearOrder()
        this.$router.push({ name: 'ComboOrderList' })
      }, 3000)
    },
    showAddBtn() {
      this.showStudent = true
      this.formStudent = {}
    },
    onSubmitb() {
      const param = { ...this.formStudent }
      if (!param.name) {
        this.$message.error(this.$t('message.qsr') + this.$t('message.xyxm'))
        return
      }
      if (param.birthday) {
        param.birthday = param.birthday + ' 00:00:00'
      }
      if (param.idCard2) {
        param.idCard = param.idCard2
      }
      param.memberId = this.memberInfo.id
      this.subStuLoading = true
      studentAdd({
        param
      })
        .then((res) => {
          this.subStuLoading = false
          if (res.errorCode === '000000') {
            this.$message.success(this.$t('message.tjcg2'))
            this.showStudent = false
            this.getStuList()
          }
        })
        .catch((err) => {
          this.subStuLoading = false
          console.log(err)
        })
    },
    getStuList() {
      studentListByMember({
        param: {
          memberId: this.memberInfo.id
        }
      })
        .then(res => {
          if (res.errorCode !== '000000') return
          this.studentList = res.recordList || []
        })
        .catch(err => {
          console.log(err)
        })
    },
    getDefalutConfig() {
      configList({ param: { type: '6' }})
        .then((res) => {
          if (res.errorCode !== '000000') return
          const list = res.recordList
          const objb = list.find(item => item.code === 'PRESENT_NUM_CONFIG')
          if (objb && objb.name) {
            this.zsnum = true
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    memberSelect(item) {
      this.memberInfo = item
      this.studentList = []
      const arr = [...this.selectedMessage]
      arr.forEach(e => {
        e.student = []
        e.students = ''
      })
      this.selectedMessage = arr
      this.getStuList()
    },
    memberClear() {
      this.$refs.MemberSearchRef.clearSearch()
      this.memberInfo = {}
      this.studentList = []
      const arr = [...this.selectedMessage]
      arr.forEach(e => {
        e.student = []
        e.students = ''
      })
      this.selectedMessage = arr
    },
    mealTitle(item) {
      let titleStr = ''
      if (item.mealsType === '0') {
        titleStr = '【' + this.$t('message.mpcsk') + '】' + item.name
      } else if (item.mealsType === '1') {
        titleStr = '【' + this.$t('message.mpqxk') + '】' + item.name
      } else if (item.mealsType === '2') {
        titleStr = '【' + this.$t('message.ydck') + '】' + item.name
      } else if (item.mealsType === '3') {
        titleStr = '【' + this.$t('message.kcyyck') + '】' + item.name
      } else if (item.mealsType === '4') {
        titleStr = '【' + this.$t('message.ykyyqxk') + '】' + item.name
      } else {
        titleStr = item.name
      }
      return titleStr.length > 30 ? titleStr.slice(0, 27) + '...' : titleStr
    },
    searchMeals() {
      this.getMeals()
    },
    mealType(item) {
      let typeStr = ''
      if (item.mealsType === '0') {
        typeStr = this.$t('message.cs') + '：' + item.nums
      } else {
        typeStr = this.$t('message.yxq') + '：' + item.indate
      }
      return typeStr
    },
    getMeals() {
      mealList({
        param: {
          name: this.mealName,
          venueId: sessionStorage.getItem('venueId')
        },
        pagination: this.salePagination
      })
        .then(res => {
          if (res.errorCode !== '000000') return
          this.saleTickets = res.recordList
          this.saleTotal = res.totalCount || 0
          this.saleTickets.forEach(item => {
            item.isSelect = false
            this.selectedMessage.forEach(select => {
              if (select.id === item.id) {
                item.isSelect = true
              }
            })
          })
        })
        .catch(err => {
          console.log(err)
        })
    },
    salePageChange(val) {
      this.salePagination.page = val
      this.getMeals()
    },
    selectTick(index) {
      const item = this.saleTickets[index]
      if (item.surplusDay < 1) {
        return this.$message.warning(this.$t('message.gkcbz'))
      }
      if (item.isSelect) {
        const index = this.selectedMessage.findIndex(i => i.id === item.id)
        this.selectedMessage.splice(index, 1)
      } else {
        if (item.mealsType === '3' || item.mealsType === '4') {
          const loading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          const venueId = sessionStorage.getItem('venueId')
          tcTeacherList({
            param: {
              venueId,
              id: item.id
            }
          })
            .then((res) => {
              if (res.errorCode === '000000') {
                this.teachList = res.recordList || []
                this.selectedMessage.push({
                  id: item.id,
                  teachList: res.recordList || [],
                  mealsType: item.mealsType,
                  nums: item.nums,
                  giveNums: item.giveNums || 0,
                  indate: item.indate,
                  name: item.name,
                  price: item.price,
                  num: 1,
                  teacherId: '',
                  student: [],
                  students: '',
                  surplusDay: item.surplusDay
                })
                loading.close()
              } else {
                loading.close()
              }
            })
            .catch(() => { loading.close() })
        } else {
          this.selectedMessage.push({
            id: item.id,
            teachList: [],
            mealsType: item.mealsType,
            nums: item.nums,
            giveNums: item.giveNums || 0,
            indate: item.indate,
            name: item.name,
            price: item.price,
            num: 1,
            teacherId: '',
            student: [],
            students: '',
            surplusDay: item.surplusDay
          })
        }
      }
      this.saleTickets[index].isSelect = !this.saleTickets[index].isSelect
    },
    clearOrder() {
      this.selectedMessage = []
      this.saleTickets.forEach(item => {
        item.isSelect = false
      })
    },
    toDelete(index) {
      this.saleTickets.forEach(item => {
        if (item.id === this.selectedMessage[index].id) {
          item.isSelect = false
        }
      })
      this.selectedMessage.splice(index, 1)
    },
    totalAction() {
      // const { remark, memberInfo } = this
      this.$refs.comboConfirm.open(this.selectedMessage, this.totalMoney)
    },
    createOrder(data) {
      const { remark, memberInfo } = this
      if (!memberInfo.id) {
        return this.$message.warning(this.$t('message.qxxzhyzjs'))
      }
      const selectedMessage = [...this.selectedMessage]
      selectedMessage.forEach(s => {
        if (s.student && s.student.length > 0) {
          s.students = s.student.join(',')
        }
      })
      const config = { selectedMessage, remark, memberInfo: memberInfo }
      this.subLoading = true
      setTimeout(() => {
        this.subLoading = false
      }, 3000)
      try {
        this.$refs.child.continuePay(config, 'combo', data.cardMessage)
      } catch (error) {
        this.subLoading = true
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/variables.scss';
.app-main-container {
  height: calc(100% - 40px);
}
.separator{
  margin: 0 20px;
  width: 1px;
  height: 100%;
  background-color: #DFE2E8;
}
.sell_left{
  height: 100%;
  .sell_wrap{
    height: calc(100% - 100px);
    overflow: auto;
  }
}

.tables {
  height: calc(100% - 200px);
  overflow: auto;
}
.card-style {
  cursor: pointer;
  width: 100%;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  padding: 10px;
  box-sizing: border-box;
  .img-div {
    width: 60px;
    height: 36px;
    margin-right: 10px;
    display: flex;
    img {
      width: 100%;
      border-radius: 2px;
    }
  }
  .combo_card_right{
    flex: 1;
    .card-name {
      margin-bottom: 10px;
      line-height: 14px;
    }
    .card_type{
      margin-bottom: 10px;
      font-size: 12px;
      line-height: 12px;
      color: #666666;
    }
    .time-style {
      color: #666666;
      margin-bottom: 12px;
      font-size: 12px;
      line-height: 12px;
    }
    .specific{
      display: flex;
      line-height: 14px;
      justify-content: space-between;
      .card-first-price {
        font-size: 14px;
      }
      .num-module-style {
        font-size: 12px;
        .sale-style {
          float: left;
        }
        .surplus-style {
          float: right;
        }
        .num-title-style {
          color: #666666;
        }
      }
    }
  }
}
.select-style {
  border: solid 1px $primaryColor;
}
.normal-style {
  border: solid 1px #d8d8d8;
}

.final_wrap {
  background: #F7F7F7;
  border-radius: 2px;
  padding: 20px;
  .price_wrap{
    display: flex;
    margin-bottom: 20px;
    .sum-style {
      font-size: 16px;
      margin-right: 75px;
      .sum-title {
        color: #222;
      }
      .sum-value {
        font-size: 17px;
        font-weight: 700;
      }
    }
  }
  .sub_order{
    display: flex;
  }
}
.count-style {
  margin-left: 5px;
  margin-right: 5px;
}
.bottom-speace-style {
  margin-bottom: 10px;
}
</style>
